package com.tencent.wxcloudrun.vpnmanagement.tools;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/*
* 拦截器，判断token合法性，被com.xjttframe.business.config.WebMvcConfig引用
* */
@Component
public class AuthenticationFilter extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtil jwtUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean isLogin = false;
        final String authHeader = request.getHeader("Authorization");
        if(authHeader!=null && authHeader.startsWith("Bearer ")){
            final String token = authHeader.substring(7);
            Claims claims = jwtUtil.parseJWT(token);

            if(claims!=null){
                if((Boolean)claims.get("isLogin")){
                    isLogin=true;
                }
            }

        }

        if(!isLogin){
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            response.getWriter().write("未通过身份认证");
        }

        return isLogin;
    }
}
